package com.rayson.yututu.manager;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.PicOperations;
import com.rayson.yututu.config.CosProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.io.InputStream;

/**
 * Author: rayson
 * Description:
 * Version: 1.0
 * Date: 2024-12-24 20:52
 */
@Component
public class CosManager {

    @Resource
    private COSClient cosClient;

    @Resource
    private CosProperties cosProperties;

    private String bucketName;

    @PostConstruct
    public void setBucketName() {
        bucketName = cosProperties.getBucket();
    }


    /**
     * 将本地文件上传到 COS
     */
    public PutObjectResult putObject(String key, File file)
            throws CosClientException {
        return cosClient.putObject(bucketName, key, file);
    }

    // 输入流上传到 COS
    public PutObjectResult putObject(String key, InputStream inputStream, ObjectMetadata metadata)
            throws CosClientException {
        return cosClient.putObject(new PutObjectRequest(bucketName, key, inputStream, metadata));
    }

    // 获取 COS 上的文件
    public COSObject getObject(String key)
            throws CosClientException {
        return cosClient.getObject(bucketName, key);
    }

    /**
     * 将本地文件上传到 COS，附带图片信息
     */
    public PutObjectResult putPictureObject(String key, InputStream inputStream, ObjectMetadata objectMetadata)
            throws CosClientException {
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, objectMetadata);
        // 对图片进行处理（获取图片信息也是处理的一种）
        PicOperations picOperations = new PicOperations();
        picOperations.setIsPicInfo(1);
        putObjectRequest.setPicOperations(picOperations);
        return cosClient.putObject(putObjectRequest);
    }
}
